import { ElMessage } from 'element-plus'
import api from '@/api'
import { useMaterials, type MaterialUsage } from './useMaterials'

export interface FeedbackForm {
  work_order_id: number | null
  description: string
  progress: number
}

export interface CompleteForm {
  work_order_id: number | null
  description: string
  fault_category: string
  materials: Array<{
    material_id: number | null
    quantity: number
    unit: string
  }>
}

export function useWorkOrderActions() {
  const { addMultipleMaterialUsage } = useMaterials()

  // 提交反馈
  const submitFeedback = async (form: FeedbackForm) => {
    try {
      await api.createProcessRecord(form.work_order_id!, {
        action: 'progress_update',
        description: `处理进度: ${form.progress}% - ${form.description}`
      })
      
      ElMessage.success('反馈提交成功')
    } catch (error) {
      console.error('提交反馈失败:', error)
      ElMessage.error('提交反馈失败')
      throw error
    }
  }

  // 完成回单
  const submitComplete = async (form: CompleteForm) => {
    if (!form.description.trim()) {
      ElMessage.error('请填写完成描述')
      return
    }
    
    try {
      // 更新工单状态
      await api.updateWorkOrder(form.work_order_id!, {
        status: 'completed',
        actual_end: new Date().toISOString(),
        custom_fields: {
          fault_category: form.fault_category,
          completion_description: form.description
        }
      })
      
      // 添加处理记录
      await api.createProcessRecord(form.work_order_id!, {
        action: 'completed',
        description: form.description
      })
      
      // 添加材料使用记录
      if (form.materials.length > 0) {
        const materialUsages: MaterialUsage[] = form.materials
          .filter(m => m.material_id && m.quantity > 0)
          .map(m => ({
            work_order_id: form.work_order_id!,
            material_id: m.material_id!,
            quantity: m.quantity,
            usage_type: '工单使用',
            purpose: '工单完成使用'
          }))
        
        if (materialUsages.length > 0) {
          await addMultipleMaterialUsage(materialUsages)
        }
      }
      
      ElMessage.success('回单成功')
    } catch (error) {
      console.error('回单失败:', error)
      ElMessage.error('回单失败')
      throw error
    }
  }

  return {
    submitFeedback,
    submitComplete
  }
}